/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.cedict.loader;

import java.io.FileNotFoundException;
import java.io.InputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cedict.dao.CedictDAO;
import org.cedict.domain.UTF8CedictRow;
import org.cedict.parser.UTF8CedictLineParser;
import org.geergenbein.dao.DAOUtils;
import org.geergenbein.parser.DocumentParser;

/**
 *
 * @author andrew
 */
public class CedictLoader {

    private Log log = LogFactory.getLog(getClass());

    private final static int TRANSACTION_SIZE = 100;

    public void load(InputStream is) {
        DocumentParser<UTF8CedictRow> parser = new DocumentParser(is,
                new UTF8CedictLineParser());
        load(parser);
    }

    /**
     * Iterate through the Unihan data and insert it into the database
     */
    public void load(String path) throws FileNotFoundException {
        DocumentParser<UTF8CedictRow> parser = new DocumentParser(path,
                new UTF8CedictLineParser());
        load(parser);
    }

    private void load(DocumentParser<UTF8CedictRow> parser) {
        CedictDAO cedictDAO = DAOUtils.getInstance().getCedictDAO();
        int count = 0;
        DAOUtils.getInstance().getTransaction().begin();
        for (UTF8CedictRow cedictRow : parser) {
//            UTF8CedictRow existingCedict = cedictDAO.
//                    findByTraditionalAndPinyin(cedictRow.
//                    getTraditionalCharacters(), cedictRow.getPinyin());
//            if (existingCedict != null) {
//                existingCedict.setSimplifiedCharacters(
//                        cedictRow.getSimplifiedCharacters());
//                existingCedict.setStringDefinitions(cedictRow.getStringDefinitions());
//                cedictRow = existingCedict;
//            }
            cedictDAO.makePersistent(cedictRow);
            if (count++ % TRANSACTION_SIZE == 0) {
                DAOUtils.getInstance().getTransaction().commit();
                cedictDAO.clear();
                DAOUtils.getInstance().getTransaction().begin();
                log.info("count=" + count);
            }
            
        }
        DAOUtils.getInstance().getTransaction().commit();
    }
}
